package historys

import (
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"github.com/gin-gonic/gin"
	"time"
)

func HistoryAll(c *gin.Context) {
	req := HistoryReq{}
	if err := c.ShouldBind(&req); err != nil {
		utils.Fail(c, errorx.VerifyError, err.Error())
	} else {
		userId := utils.CtxUserId(c)
		historyInfo := []models.History{}
		var Count int64
		//tx := global.APP.DB.Where("user_id=?", userId).Limit(int(req.Page)).Offset(int(req.Limit) - 1).Find(&historyInfo).Count(&Count).
		scan := global.APP.DB.Raw("SELECT * FROM histories WHERE user_id=? and deleted_at IS Null LIMIT ?,?", userId, req.Limit-1, req.Page).Scan(&historyInfo).Count(&Count)

		if scan.Error != nil {
			global.APP.Log.Error(scan.Error.Error())
			utils.Fail(c, 70000, scan.Error.Error())
		} else {
			userInfo := models.User{}
			global.APP.DB.Where("id=?", userId).First(&userInfo) // 查询用户数据，将用户名传给前端进行展示
			history_info := []map[string]interface{}{}
			for _, item := range historyInfo {
				history_info = append(history_info, map[string]interface{}{
					"ID":       item.ID,
					"username": userInfo.Username,
					//"Path":           item.Path,
					"api":             item.API,
					"operation_type":  item.OperationType,
					"request_address": item.RequestAddress,
					"create_at":       item.CreatedAt.Format(time.DateTime),
				})
			}
			//fmt.Println(history_info)
			utils.Success(c, Count, history_info)
		}
	}

}
